<template>
  <div class="create-group-page">
    <!-- 群名称输入 -->
    <van-field
        v-model="groupInfo.groupName"
        label="群名称："
        placeholder="请输入群名称"
        name="groupName"
        class="group-name"
        @blur="validateGroupName"
    />

    <!-- 群头像上传 -->
    <div class="group-avatar-container">
      <span style="font-size: 14px;margin-bottom: 20px">群头像</span>
      <van-col span="18">

        <label for="file-upload" class="avatar-label">
          <img src="../../assets/images/add.png" alt="Choose Avatar" style="width: 30px;"/>
        </label>
        <input
            type="file"
            id="file-upload"
            ref="groupAvatarInput"
            style="display: none;"
            @change="handleImageUpload"
        />
        <!-- 头像预览区域 -->
        <div v-if="groupInfo.iconUrl" class="image-preview-container">
          <img :src="groupInfo.iconUrl" alt="Image Preview" class="image-preview" />
        </div>
      </van-col>
    </div>

    <!-- 创建按钮 -->
    <van-button
        type="primary"
        class="create-group-button"
        @click="submitGroup"
        :disabled="!isFormValid || !groupInfo.iconFile"
    >
      立即创建
    </van-button>
  </div>
</template>


<script>
import { ref, reactive } from 'vue';
import { Field, Button, Col,Toast} from 'vant';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { uploadPic } from '@/v-api/login/index.js';
export default {
  components: {
    'van-field': Field,
    'van-button': Button,
    'van-col': Col,
  },
  setup() {
    const groupInfo = reactive({
      groupName: '',
      iconUrl: '',
      iconFile: null,
    });

    const isFormValid = ref(false);
    const router = useRouter();

    const validateGroupName = () => {
      isFormValid.value = !!groupInfo.groupName.trim();
    };


    const handleImageUpload = async event => {
      const file = event.target.files[0];
      if (file) {
        groupInfo.iconUrl = URL.createObjectURL(file);

        // 使用uploadPic函数上传文件
        const filePath = await uploadPic({ file: file });
        if (filePath) {
          groupInfo.iconFile = filePath;
        } else {
          throw new Error('文件上传失败');
        }
      }
    };
    const submitGroup = async () => {
      if (!isFormValid.value || !groupInfo.groupName || !groupInfo.iconFile) {
        alert('请完成所有必填项');
        return;
      }

      // 创建一个对象来存储其他数据
      const submissionData = {
        groupName: groupInfo.groupName,
        iconUrl: groupInfo.iconFile, // 发送文件标识符
      };
      try {
        const response = await axios.post('/api/group-contacts/create', submissionData,
        );
        if (response.status === 200) { // 检查HTTP状态码
          if (response.data.code === 2000) { // 检查业务逻辑状态码
            Toast.success('群聊创建成功')

            router.back()
          } else {
            Toast.fail('创建失败：' + response.data.message);

          }
        } else {
          throw new Error('服务器响应异常');
        }
      } catch (error) {
        console.error("提交失败：", error);
        alert("提交失败：" + error.message || '未知错误');
      }
    };

    return {
      groupInfo,
      validateGroupName,
      handleImageUpload,
      submitGroup,
      isFormValid,
    };
  },
};
</script>









<style scoped>
.create-group-page {
  max-width: 500px;
  margin: 0 auto;
  padding: 20px;
  margin: 10px;
}
.group-name, .group-avatar-container {
  border: 2px solid #9caf70; /* 边框颜色 */
  border-radius: 8px; /* 边框圆角 */
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1); /* 阴影效果 */
  padding: 20px;
  margin-top: 20px;
  text-align: left;
}


.create-group-button {
  margin-top: 80px;
  margin-left: 120px;
}
.image-preview-container {
  margin-top: 10px;
  text-align: center;
}
.image-preview {
  max-width: 100px;
  border-radius: 50%; /* 圆形头像 */
  object-fit: cover;
}
</style>